﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;

using com.crawler.db.Interface;
using com.crawler.common;
using System.Reflection;
using System.IO;
using System.Text.RegularExpressions;
using System.Data.SqlClient;

namespace com.crawler.db.SQL2000
{
    public class DataAccess : DataManager
    {
        private static object m_single_obj = new object();

        /// <summary>
        /// 获取小说信息
        /// </summary>
        /// <param name="i_book_id"></param>
        /// <param name="i_connect_string"></param>
        /// <returns></returns>
        public BookInfo GetBookInfoById(long i_book_id, string i_connect_string)
        {
            string t_str_sql = string.Format("select bookName,AuthorName,categoryName,subCategoryName,Description,siteId,siteName,lastUpdateChapterId,lastUpdateChapterName,lastUpdateTime,chapterListUrl,chapterCount from tbbook where bookId={0}", i_book_id);

            BookInfo t_book = null;

            try
            {
                DataSet t_ds = DBHelper.Query(t_str_sql, i_connect_string);
                if (t_ds != null && t_ds.Tables.Count > 0 && t_ds.Tables[0].Rows.Count > 0)
                {
                    t_book = new BookInfo();
                    t_book.BookId = i_book_id;
                    t_book.ChapterListUrl = t_ds.Tables[0].Rows[0]["chapterListUrl"].ToString();
                    t_book.BookName = t_ds.Tables[0].Rows[0]["bookName"].ToString();
                    t_book.AuthorName = t_ds.Tables[0].Rows[0]["AuthorName"].ToString();
                    t_book.CategoryName = t_ds.Tables[0].Rows[0]["categoryName"].ToString();
                    t_book.SubCategoryName = t_ds.Tables[0].Rows[0]["subCategoryName"].ToString();
                    t_book.Description = t_ds.Tables[0].Rows[0]["Description"].ToString();
                    t_book.SiteId = Convert.ToInt32(t_ds.Tables[0].Rows[0]["SiteId"].ToString());
                    t_book.SiteName = t_ds.Tables[0].Rows[0]["siteName"].ToString();
                    t_book.LastUpdateChapterId = t_ds.Tables[0].Rows[0]["lastUpdateChapterId"] == DBNull.Value ? 0 : Convert.ToInt32(t_ds.Tables[0].Rows[0]["lastUpdateChapterId"].ToString());
                    t_book.LastUpdateChapterName = t_ds.Tables[0].Rows[0]["lastUpdateChapterName"] == DBNull.Value ? "" : t_ds.Tables[0].Rows[0]["lastUpdateChapterName"].ToString();
                    t_book.LastUpdateChapterTime = t_ds.Tables[0].Rows[0]["lastUpdateTime"] == DBNull.Value ? DateTime.Now : Convert.ToDateTime(t_ds.Tables[0].Rows[0]["lastUpdateTime"].ToString());
                    t_book.ChapterCount = t_ds.Tables[0].Rows[0]["chapterCount"] == DBNull.Value ? 0 : Convert.ToInt32(t_ds.Tables[0].Rows[0]["chapterCount"].ToString());
                }

                return t_book;
            }
            catch (Exception ex)
            {
                throw new DataException("获取小说信息失败", ex);
            }
        }

        /// <summary>
        /// 插入站点信息
        /// </summary>
        /// <param name="i_site_id"></param>
        /// <param name="i_site_name"></param>
        /// <param name="i_tb_name"></param>
        /// <param name="i_connect_string"></param>
        /// <returns></returns>
        public int InsertBookSite(int i_site_id, string i_site_name, string i_tb_name, string i_site_enconding, string i_chapter_content_reg, string i_chapter_content_filter, string i_connect_string)
        {
            try
            {

                StringBuilder t_sb = new StringBuilder();
                t_sb.Append("insert into tbBookSite(siteId,siteName,tbName,siteEnconding,chapterContentReg,chapterContentFilter)values");


                t_sb.AppendFormat("({0},'{1}','{2}','{3}','{4}','{5}')", i_site_id, i_site_name, i_tb_name, i_site_enconding, i_chapter_content_reg, i_chapter_content_filter);


                return DBHelper.ExecuteSql(t_sb.ToString(), i_connect_string);

            }
            catch (Exception ex)
            {
                throw new DataException("插入站点信息失败", ex);
            }
        }

        /// <summary>
        /// 初始化站点到数据库
        /// </summary>
        /// <param name="i_book_site_list"></param>
        /// <returns></returns>
        public int InitBookSite(List<BookSiteInfo> i_book_site_list, string i_connect_string)
        {
            string t_str_sql = "delete from tbbookSite";

            try
            {
                DBHelper.ExecuteSql(t_str_sql, i_connect_string);


                StringBuilder t_sb = new StringBuilder();

                foreach (BookSiteInfo t_site in i_book_site_list)
                {
                    t_sb.Append("insert into tbBookSite(siteId,siteName,tbName,siteEnconding,chapterContentReg,chapterContentFilter)values");

                    t_sb.AppendFormat("({0},'{1}','{2}','{3}','{4}','{5}')", t_site.SiteId, t_site.SiteName, t_site.TbName, t_site.SiteEncoding, t_site.ChapterContentReg, t_site.ChapterContentFilterReg);
                    DBHelper.ExecuteSql(t_sb.ToString(), i_connect_string);
                    t_sb = new StringBuilder();

                }

                return 1;

            }
            catch (Exception ex)
            {
                throw new DataException("初始化站点信息失败", ex);
            }
        }
        /// <summary>
        /// 获取站点图书信息
        /// </summary>
        /// <param name="i_book_name"></param>
        /// <param name="i_site_id"></param>
        /// <param name="i_connect_string"></param>
        /// <returns></returns>
        public BookInfo GetBookInfoByName(string i_book_name, string i_connect_string)
        {

            lock (m_single_obj)
            {
                try
                {

                    BookInfo t_book = null;
                    string t_sql = string.Format("select bookId,ChapterListUrl,lastUpdateChapterName from tbbook where bookName='{0}' ", i_book_name);
                    DataSet t_ds = DBHelper.Query(t_sql, i_connect_string);
                    if (t_ds != null && t_ds.Tables.Count > 0 && t_ds.Tables[0].Rows.Count > 0)
                    {
                        t_book = new BookInfo();
                        t_book.BookId = Convert.ToInt64(t_ds.Tables[0].Rows[0]["bookId"].ToString());
                        t_book.ChapterListUrl = t_ds.Tables[0].Rows[0]["ChapterListUrl"].ToString();
                        t_book.BookName = i_book_name;
                        t_book.LastUpdateChapterName = t_ds.Tables[0].Rows[0]["LastUpdateChapterName"].ToString();


                    }
                    return t_book;

                }
                catch (Exception ex)
                {
                    throw new DataException("获取图书信息失败", ex);
                }
            }
        }

        /// <summary>
        /// 批量插入章节信息
        /// </summary>
        /// <param name="i_book_id"></param>
        /// <param name="i_book_name"></param>
        /// <param name="i_chapter_list"></param>
        /// <param name="i_connect_string"></param>
        /// <param name="i_table_name"></param>
        /// <returns></returns>
        public int AddChapterList(long i_book_id, string i_book_name, List<ChapterInfo> i_chapter_list, string i_connect_string, string i_table_name, int i_site_id, string i_site_name)
        {
            lock (m_single_obj)
            {
                string t_book_status = i_table_name;

                i_table_name = "tbchapter";

                if (i_chapter_list == null || i_chapter_list.Count == 0)
                    return 0;

                int t_chapter_index = 0;
                long t_chapter_id = 0;
                long t_pre_chapter_id = 0;
                long t_next_chapter_id = 0;
                long t_last_chapter_id = 0;//上次更新的最后一个章节ID
                long t_now_first_chapter_id = 0;//本次更新的最新一个ID

                DataSet t_ds = null;

                string t_sql = string.Empty;
                try
                {

                    t_sql = string.Format("select top 1 chapterId,chapterIndex from {0} where bookId={1} order by chapterId desc ", i_table_name, i_book_id);

                    t_ds = DBHelper.Query(t_sql, i_connect_string);

                    if (t_ds != null && t_ds.Tables[0].Rows.Count > 0)
                    {
                        if (!long.TryParse(t_ds.Tables[0].Rows[0]["chapterId"].ToString(), out t_pre_chapter_id))
                            t_pre_chapter_id = 0;
                        t_last_chapter_id = t_pre_chapter_id;
                        if (!int.TryParse(t_ds.Tables[0].Rows[0]["chapterIndex"].ToString(), out t_chapter_index))
                            t_chapter_index = 0;


                    }


                    if (t_chapter_index == i_chapter_list.Count - 1)
                        return 0;

                    if (t_chapter_index != 0)
                    {
                        t_chapter_index = t_chapter_index + 1;
                    }

                    t_sql = string.Format("select top 1 chapterId from {0} order by chapterId desc ", i_table_name);

                    t_ds = DBHelper.Query(t_sql, i_connect_string);
                    if (t_ds != null && t_ds.Tables[0].Rows.Count > 0)
                    {
                        if (!long.TryParse(t_ds.Tables[0].Rows[0]["chapterId"].ToString(), out t_chapter_id))
                            t_chapter_id = 0;

                    }

                    t_chapter_id++;
                    t_now_first_chapter_id = t_chapter_id;



                    DataTable t_dt = new DataTable();
                    t_dt.Columns.Add("bookId", typeof(long));
                    t_dt.Columns.Add("chapterName", typeof(string));
                    t_dt.Columns.Add("chapterUrl", typeof(string));
                    t_dt.Columns.Add("bookName", typeof(string));
                    t_dt.Columns.Add("updateTime", typeof(DateTime));
                    t_dt.Columns.Add("preChapterId", typeof(long));
                    t_dt.Columns.Add("nextChapterId", typeof(long));
                    t_dt.Columns.Add("chapterId", typeof(long));
                    t_dt.Columns.Add("chapterIndex", typeof(int));

                    t_next_chapter_id = t_chapter_id + 1;

                    for (int index = t_chapter_index; index < i_chapter_list.Count; index++)
                    {
                        DataRow t_dr = t_dt.NewRow();
                        t_dr["bookId"] = i_book_id;
                        t_dr["chapterName"] = i_chapter_list[index].ChapterName.Replace("'", "");
                        t_dr["chapterUrl"] = i_chapter_list[index].ChapterUrl.Replace("'", "");
                        t_dr["bookName"] = i_book_name.Replace("'", "");
                        t_dr["updateTime"] = i_chapter_list[index].UpdateTime;
                        t_dr["preChapterId"] = t_pre_chapter_id;
                        t_dr["nextChapterId"] = (index == i_chapter_list.Count - 1) ? 0 : t_next_chapter_id;
                        t_dr["chapterId"] = t_chapter_id;
                        t_dr["chapterIndex"] = index;
                        t_dt.Rows.Add(t_dr);

                        t_pre_chapter_id = t_chapter_id;
                        t_chapter_id = t_next_chapter_id;
                        t_next_chapter_id++;
                    }

                    using (SqlConnection t_con = new SqlConnection(i_connect_string))
                    {
                        t_con.Open();
                        using (SqlBulkCopy t_sql_sbc = new SqlBulkCopy(t_con))
                        {
                            t_sql_sbc.DestinationTableName = i_table_name;
                            t_sql_sbc.BatchSize = t_dt.Rows.Count;
                            t_sql_sbc.ColumnMappings.Add("bookId", "bookId");
                            t_sql_sbc.ColumnMappings.Add("chapterName", "chapterName");
                            t_sql_sbc.ColumnMappings.Add("chapterUrl", "chapterUrl");
                            t_sql_sbc.ColumnMappings.Add("bookName", "bookName");
                            t_sql_sbc.ColumnMappings.Add("updateTime", "updateTime");
                            t_sql_sbc.ColumnMappings.Add("preChapterId", "preChapterId");
                            t_sql_sbc.ColumnMappings.Add("nextChapterId", "nextChapterId");
                            t_sql_sbc.ColumnMappings.Add("chapterId", "chapterId");
                            t_sql_sbc.ColumnMappings.Add("chapterIndex", "chapterIndex");
                            t_sql_sbc.WriteToServer(t_dt);
                        }
                        if (t_con.State == ConnectionState.Open)
                        {
                            t_con.Close();
                        }

                    }


                    if (t_last_chapter_id > 0)
                    {
                        t_sql = string.Format("update {0} set nextChapterId={1} where chapterId={2}", i_table_name, t_now_first_chapter_id, t_last_chapter_id);

                        DBHelper.ExecuteSql(t_sql, i_connect_string);
                    }
                    t_sql = string.Format("update tbBook set lastUpdateChapterId={0},lastUpdateChapterName='{1}',lastUpdateTime='{2}',chapterCount={3},siteId={4},siteName='{5}',isDownLoad=1 where bookId={6}",
          t_pre_chapter_id, i_chapter_list[i_chapter_list.Count - 1].ChapterName, i_chapter_list[i_chapter_list.Count - 1].UpdateTime, i_chapter_list.Count, i_site_id, i_site_name, i_book_id);

                    DBHelper.ExecuteSql(t_sql, i_connect_string);

                    return i_chapter_list.Count - t_chapter_index;
                }
                catch (Exception ex)
                {
                    LogHelper.Info("添加小说章节失败,bookId=" + i_book_id.ToString() + ",bookName=" + i_book_name + ",constring=" + i_connect_string + ",str_sql=" + t_sql);
                    throw new DataException("批量插入小说章节失败", ex);
                }
            }
        }



        /// <summary>
        /// 添加小说信息
        /// </summary>
        /// <param name="i_book"></param>
        /// <returns></returns>
        public long AddBook(BookInfo i_book, string i_connect_string)
        {
            lock (m_single_obj)
            {
                try
                {
                    i_book.Description = Regex.Replace(i_book.Description, "<[^<>]*?>", "<br>", RegexOptions.IgnoreCase);
                    i_book.Description = CrawlerUtil.GetGBString(i_book.Description, 1900);

                    long t_book_id = 0;



                    string t_str_sql = string.Format("select bookId,bookName from tbbook where bookName='{0}'", i_book.BookName.Replace("'", ""));
                    DataSet t_ds = DBHelper.Query(t_str_sql, i_connect_string);

                    if (t_ds != null && t_ds.Tables[0].Rows.Count > 0)
                    {
                        if (!long.TryParse(t_ds.Tables[0].Rows[0]["bookId"].ToString(), out t_book_id))
                            t_book_id = -1;
                    }


                    if (t_book_id > 0)
                    {
                        return t_book_id;
                    }



                    t_str_sql = "insert into tbbook(bookName,AuthorName,categoryName,subCategoryName,ICONUrl,ChapterListUrl,Description,siteId,siteName,status)" +
                    string.Format("values('{0}','{1}','{2}','{3}','{4}','{5}','{6}',{7},'{8}',1)", i_book.BookName.Replace("'", ""), i_book.AuthorName.Replace("'", ""), i_book.CategoryName.Replace("'", ""),
                    i_book.SubCategoryName.Replace("'", ""), i_book.ICONUrl.Replace("'", ""), i_book.ChapterListUrl.Replace("'", ""), i_book.Description.Replace("'", ""), i_book.SiteId, i_book.SiteName);

                    int t_ret = DBHelper.ExecuteSql(t_str_sql, i_connect_string);

                    if (t_ret > 0)
                    {
                        t_str_sql = string.Format("select bookId from tbbook where  bookName='{0}'", i_book.BookName.Replace("'", ""));
                        t_ds = DBHelper.Query(t_str_sql, i_connect_string);

                        if (t_ds != null && t_ds.Tables[0].Rows.Count > 0)
                        {
                            if (!long.TryParse(t_ds.Tables[0].Rows[0]["bookId"].ToString(), out t_book_id))
                                t_book_id = -1;
                        }


                    }
                    return t_book_id;

                }
                catch (Exception ex)
                {
                    LogHelper.Info("添加小说信息失败" + ex.ToString() + "bookInfo=" + i_book.ToString() + "connstring=" + i_connect_string);
                    throw new DataException("添加小说信息失败", ex);
                }

            }

        }

        /// <summary>
        /// 添加章节信息
        /// </summary>
        /// <param name="i_chapter"></param>
        /// <returns></returns>
        public long AddChapter(ChapterInfo i_chapter, string i_connect_string, string i_table_name)
        {
            string t_sql = "insert into tbChapter(bookId,,ChapterName,ChapterUrl,BookName,UpdateTime,PreChapterId,NextChapterId)" +
             string.Format("values({0},'{1}','{2}','{3}','{4}',{5},{6})", i_chapter.BookId, i_chapter.ChapterName, i_chapter.ChapterUrl,
             i_chapter.BookName, i_chapter.UpdateTime, i_chapter.PreChapterId, i_chapter.NextChapterId);

            try
            {
                return DBHelper.ExecuteSql(t_sql, i_connect_string);
            }
            catch (Exception ex)
            {
                throw new DataException("添加小说信息失败", ex);
            }
        }

        /// <summary>
        /// 获取某本小说的最后更新章节ID
        /// </summary>
        /// <param name="i_book_id"></param>
        /// <returns></returns>
        public long GetLastUpdateChapterId(long i_book_id, string i_connect_string, string i_table_name)
        {
            string t_sql = string.Format("select max(chapterId) chapterId from {0} where bookId={1}", i_table_name, i_book_id);

            long t_last_update_chapter_id = 0;
            try
            {
                DataSet ds = DBHelper.Query(t_sql, i_connect_string);

                if (ds != null && ds.Tables.Count > 0)
                {
                    if (!long.TryParse(ds.Tables[0].Rows[0]["chapterId"].ToString(), out t_last_update_chapter_id))
                        t_last_update_chapter_id = 0;
                }
                return t_last_update_chapter_id;
            }
            catch (Exception ex)
            {
                throw new DataException("获取小说：" + i_book_id.ToString() + "的最新更新章节ID失败", ex);
            }
        }

        /// <summary>
        /// 更新书籍最近跟新时间
        /// </summary>
        /// <param name="i_book_id"></param>
        /// <param name="i_last_update_chapter_id"></param>
        /// <param name="i_last_update_chapter_name"></param>
        /// <param name="i_last_update_time"></param>
        /// <param name="i_connect_string"></param>
        /// <returns></returns>
        public int UpdateBook(long i_book_id, string i_connect_string, string i_table_name, int i_chapter_count)
        {
            /*
            string t_sql = string.Format("update tbBook set lastUpdateChapterId={0},lastUpdateChapterName='{1}',lastUpdateTime='{2}' where bookId={3}",
                i_last_update_chapter_id, i_last_update_chapter_name, i_last_update_time, i_book_id);

            try
            {
                return DBHelper.ExecuteSql(t_sql, i_connect_string);
            }
            catch (Exception ex)
            {
                throw new DataException("更新小说最新更新章节信息失败", ex);
            }*/
            return -1;
        }

        /// <summary>
        /// 创建表结构
        /// </summary>
        /// <param name="i_table_name"></param>
        /// <param name="i_connect_string"></param>
        /// <returns></returns>
        public int CreateTable(string i_table_name, string i_connect_string)
        {
            string t_sql = LoadSqlFromAssembly("CreateTable.txt");

            if (!string.IsNullOrEmpty(t_sql))
            {
                t_sql = string.Format(t_sql, i_table_name);

            }

            try
            {
                return DBHelper.ExecuteSql(t_sql, i_connect_string);
            }
            catch (Exception ex)
            {
                throw new DataException("创建表结构失败", ex);
            }
        }

        /// <summary>
        /// 更新小说下载状态
        /// </summary>
        /// <param name="i_chapter_id"></param>
        /// <param name="i_connect_string"></param>
        /// <returns></returns>
        public int UpdateChapter(long i_book_id, long i_chapter_id, string i_chapter_url, BookUrlInfo i_book_url, string i_connect_string)
        {
            string t_str_sql = string.Format("update tbchapter set isDownLoad=1,chapterUrl='{0}' where chapterId={1}", i_chapter_url, i_chapter_id);

            try
            {
                if (!string.IsNullOrEmpty(i_book_url.ChapterListUrl))
                {
                    AddBookUrl(i_book_id, i_book_url.ChapterListUrl,i_book_url.SartIndex,i_book_url.StartSign,i_book_url.EndSign, i_connect_string);
                }

                return DBHelper.ExecuteSql(t_str_sql, i_connect_string);
            }
            catch (Exception ex)
            {
                throw new DataException("更新章节下载状态失败", ex);
            }
        }

        /// <summary>
        /// 添加小说URL
        /// </summary>
        /// <param name="i_book_url"></param>
        /// <returns></returns>
        private int AddBookUrl(long i_book_id, string i_chapter_list_url,int i_start_index,string i_start_sign,string i_end_sign, string i_connect_string)
        {
            Uri t_u = new Uri(i_chapter_list_url);

            string t_str_sql = string.Format("select count(*) totalcount from tbbookUrl where bookId={0} and host='{1}'", i_book_id, t_u.Host);

            try
            {
                DataSet t_ds = DBHelper.Query(t_str_sql, i_connect_string);
                int t_count = 0;
                if (t_ds != null && t_ds.Tables[0].Rows.Count > 0)
                {
                    if (!int.TryParse(t_ds.Tables[0].Rows[0]["totalcount"].ToString(), out t_count))
                        t_count = 0;
                }
                if (t_count <= 0)
                {
                    
                    i_chapter_list_url = i_chapter_list_url.Replace("'", "''");
                    i_start_sign = i_start_sign.Replace("'", "''");
                    i_end_sign = i_end_sign.Replace("'", "''");

                    t_str_sql = string.Format("insert tbbookUrl(bookId,host,bits,chapterlisturl,startIndex,startSign,endSign)values({0},'{1}',{2},'{3}',{4},'{5}','{6}')", 
                        i_book_id, t_u.Host, 1, i_chapter_list_url,i_start_index,i_start_sign,i_end_sign);

                    return DBHelper.ExecuteSql(t_str_sql, i_connect_string);
                }
                return -1;
            }
            catch (Exception ex)
            {
                LogHelper.Error("添加小说URL" + ex.ToString());
                return -1;
            }
        }

        public List<BookInfo> GetSEOBook(string i_connect_string)
        {
            string t_str_sql = "select a.bookId,a.bookName,a.siteId,siteName, a.chapterlisturl,a.lastUpdateChapterName, a.lastUpdateTime,a.status,a.isdownload from tbbook a,tbbookclick b where a.bookid=b.bookid order by b.clickcount desc";

            List<BookInfo> t_book_list = null;

            DateTime t_last_update_time = DateTime.Now.AddDays(-1);

            Dictionary<int, List<BookInfo>> t_dic = new Dictionary<int, List<BookInfo>>();

            try
            {
                DataSet t_ds = DBHelper.Query(t_str_sql, i_connect_string);

                if (t_ds != null && t_ds.Tables.Count > 0 && t_ds.Tables[0].Rows.Count > 0)
                {
                    BookInfo t_book = null;

                    t_book_list = new List<BookInfo>();

                    foreach (DataRow t_dr in t_ds.Tables[0].Rows)
                    {
                       
                        if (t_dr["lastUpdateChapterName"] != DBNull.Value)
                        {
                            if (IsComplateBook(t_dr["lastUpdateChapterName"].ToString()))
                                continue;
                        }
                        //if (t_dr["isdownload"] != DBNull.Value)
                        //{
                        //    if (t_dr["isdownload"].ToString() == "-1") //已经被删除
                        //        continue;
                        //}

                        if (t_dr["lastUpdateTime"] != DBNull.Value)
                        {
                            if (!DateTime.TryParse(t_dr["lastUpdateTime"].ToString(), out t_last_update_time))
                                t_last_update_time = DateTime.Now.AddDays(-1);
                        }

                        //才更新5个小时的小说不要再更新
                        if (t_last_update_time.AddHours(5) >= DateTime.Now)
                            continue;

                        t_book = new BookInfo();
                        t_book.ChapterListUrl = t_dr["chapterlisturl"].ToString();
                        t_book.BookId = Convert.ToInt64(t_dr["bookId"].ToString());
                        t_book.BookName = t_dr["bookName"].ToString();
                        t_book.SiteId = Convert.ToInt32(t_dr["siteId"].ToString());
                        t_book.SiteName = t_dr["siteName"].ToString();
                        t_book.Status = t_dr["status"] == DBNull.Value ? "1" : t_dr["status"].ToString();

                        if (!t_dic.ContainsKey(t_book.SiteId))
                        {
                            List<BookInfo> t_list = new List<BookInfo>();
                            t_list.Add(t_book);
                            t_dic.Add(t_book.SiteId, t_list);
                        }
                        else
                        {
                            t_dic[t_book.SiteId].Add(t_book);
                        }

                    }

                    int t_max_site_count = 0;
                    foreach (int t_key in t_dic.Keys)
                    {
                        if (t_dic[t_key].Count > t_max_site_count)
                            t_max_site_count = t_dic[t_key].Count;
                    }

                    for (int index = 0; index < t_max_site_count; index++)
                    {
                        foreach (int t_key in t_dic.Keys)
                        {
                            if (t_dic[t_key].Count > index)
                            {
                                t_book_list.Add(t_dic[t_key][index]);
                            }
                        }
                    }
                }
                return t_book_list;
            }
            catch (Exception ex)
            {
                LogHelper.Error("获取重点更新列表失败" + ex.ToString());
                return null;
            }
        }


        /// <summary>
        /// 获取需要更新的小说章节内容的小说
        /// </summary>
        /// <param name="i_connect_string"></param>
        /// <returns></returns>
        public List<BookInfo> GetSEOBookChapterContent(string i_connect_string)
        {
            string t_str_sql = "select * from (select a.bookId,a.siteId,a.chapterlisturl,a.lastUpdateChapterName, a.lastUpdateTime,a.isdownload,b.clickcount clickcount from tbbook a,tbbookclick b where a.bookid=b.bookid union select a.bookId,a.siteId,a.chapterlisturl,a.lastUpdateChapterName, a.lastUpdateTime,a.isdownload,1 clickcount from tbbook a,tbbookurl b where a.bookId=b.bookId) t order by t.clickcount desc";

            List<BookInfo> t_book_list = null;

            DateTime t_last_update_time = DateTime.Now.AddDays(-1);

            Dictionary<int, List<BookInfo>> t_dic = new Dictionary<int, List<BookInfo>>();

            try
            {
                DataSet t_ds = DBHelper.Query(t_str_sql, i_connect_string);

                if (t_ds != null && t_ds.Tables.Count > 0 && t_ds.Tables[0].Rows.Count > 0)
                {
                    BookInfo t_book = null;

                    t_book_list = new List<BookInfo>();

                    foreach (DataRow t_dr in t_ds.Tables[0].Rows)
                    {

                        if (t_dr["lastUpdateChapterName"] != DBNull.Value)
                        {
                            if (IsComplateBook(t_dr["lastUpdateChapterName"].ToString()))
                                continue;
                        }
                        if (t_dr["isdownload"] != DBNull.Value)
                        {
                            if (t_dr["isdownload"].ToString() == "-1") //已经被删除
                                continue;
                        }

                        if (t_dr["lastUpdateTime"] != DBNull.Value)
                        {
                            if (!DateTime.TryParse(t_dr["lastUpdateTime"].ToString(), out t_last_update_time))
                                t_last_update_time = DateTime.Now.AddDays(-1);
                        }

                        //才更新5个小时的小说不要再更新
                        if (t_last_update_time.AddHours(5) >= DateTime.Now)
                            continue;

                        t_book = new BookInfo();
                        t_book.BookId = Convert.ToInt64(t_dr["bookId"].ToString());
                        t_book.SiteId = Convert.ToInt32(t_dr["siteId"].ToString());
                    
                        if (!t_dic.ContainsKey(t_book.SiteId))
                        {
                            List<BookInfo> t_list = new List<BookInfo>();
                            t_list.Add(t_book);
                            t_dic.Add(t_book.SiteId, t_list);
                        }
                        else
                        {
                            t_dic[t_book.SiteId].Add(t_book);
                        }

                    }

                    int t_max_site_count = 0;
                    foreach (int t_key in t_dic.Keys)
                    {
                        if (t_dic[t_key].Count > t_max_site_count)
                            t_max_site_count = t_dic[t_key].Count;
                    }

                    for (int index = 0; index < t_max_site_count; index++)
                    {
                        foreach (int t_key in t_dic.Keys)
                        {
                            if (t_dic[t_key].Count > index)
                            {
                                t_book_list.Add(t_dic[t_key][index]);
                            }
                        }
                    }
                }
                return t_book_list;
            }
            catch (Exception ex)
            {
                LogHelper.Error("获取重点更新列表失败" + ex.ToString());
                return null;
            }
        }


        public List<BookInfo> GetVIPBook(string i_connect_string)
        {
            string t_str_sql = "select a.bookId,a.bookName,a.siteId,siteName, a.chapterlisturl,lastUpdateChapterName,a.lastUpdateTime,a.status,a.isdownload from tbbook a where  a.bookId not in (select bookId from tbbookclick)";

            List<BookInfo> t_book_list = null;
            DateTime t_last_update_time = DateTime.Now.AddDays(-1);
            try
            {
                DataSet t_ds = DBHelper.Query(t_str_sql, i_connect_string);

                if (t_ds != null && t_ds.Tables.Count > 0 && t_ds.Tables[0].Rows.Count > 0)
                {
                    BookInfo t_book = null;

                    t_book_list = new List<BookInfo>();

                    foreach (DataRow t_dr in t_ds.Tables[0].Rows)
                    {
                        if (t_dr["lastUpdateChapterName"] != DBNull.Value)
                        {
                            if (IsComplateBook(t_dr["lastUpdateChapterName"].ToString()))
                                continue;
                        }

                        //if (t_dr["isdownload"] != DBNull.Value)
                        //{
                        //    if (t_dr["isdownload"].ToString() == "-1") //已经被删除
                        //        continue;
                        //}

                        if (t_dr["lastUpdateTime"] != DBNull.Value)
                        {
                            if (!DateTime.TryParse(t_dr["lastUpdateTime"].ToString(), out t_last_update_time))
                                t_last_update_time = DateTime.Now.AddDays(-1);
                        }

                        //才更新5个小时的小说不要再更新
                        if (t_last_update_time.AddHours(5)>=DateTime.Now)
                            continue;

                        t_book = new BookInfo();
                        t_book.ChapterListUrl = t_dr["chapterlisturl"].ToString();
                        t_book.BookId = Convert.ToInt64(t_dr["bookId"].ToString());
                        t_book.BookName = t_dr["bookName"].ToString();
                        t_book.Status = t_dr["status"] == DBNull.Value ? "1" : t_dr["status"].ToString();

                        t_book.SiteId = Convert.ToInt32(t_dr["siteId"].ToString());
                        t_book.SiteName = t_dr["siteName"].ToString();

                        t_book.IsVIP = true;
                        t_book_list.Add(t_book);
                    }
                }
                return t_book_list;
            }
            catch (Exception ex)
            {
                LogHelper.Error("获取重点更新列表失败" + ex.ToString());
                return null;
            }
        }
        /// <summary>
        /// 获取需要更新章节的图书列表
        /// </summary>
        /// <returns></returns>
        public List<BookInfo> GetUpdateBookList(string i_connect_string)
        {
            string t_str_sql = string.Format("select a.bookId,a.bookName,c.siteId,siteName, c.chapterlisturl,lastUpdateChapterId,lastUpdateChapterName,ChapterCount from tbbook a,tbbookclick b,tbcrawlerbook c where a.bookId=b.bookId and c.bookName=a.bookName and c.siteId in({0}) order by b.clickcount desc", Consts.ExistChapterSiteIdList);
            //t_str_sql = "select a.bookId,a.bookName,6 siteId, '万书吧' siteName, 'http://www.wanshuba.com/Html/6/6989/List.html' chapterlisturl,lastUpdateChapterId,lastUpdateChapterName,ChapterCount from tbbook a where a.bookId=468";
            List<BookInfo> t_list = null;
            try
            {
                DataSet t_ds = DBHelper.Query(t_str_sql, i_connect_string);

                if (t_ds != null && t_ds.Tables.Count > 0 && t_ds.Tables[0].Rows.Count > 0)
                {
                    BookInfo t_book = null;

                    t_list = new List<BookInfo>();

                    foreach (DataRow t_dr in t_ds.Tables[0].Rows)
                    {
                        if (Convert.ToInt32(t_dr["siteId"].ToString()) == 5)
                            continue;
                        t_book = new BookInfo();
                        t_book.ChapterListUrl = t_dr["chapterlisturl"].ToString();
                        t_book.BookId = Convert.ToInt64(t_dr["bookId"].ToString());
                        t_book.BookName = t_dr["bookName"].ToString();
                        t_book.LastUpdateChapterName = t_dr["lastUpdateChapterName"].ToString();
                        t_book.LastUpdateChapterId = t_dr["lastUpdateChapterId"] == DBNull.Value ? 0 : Convert.ToInt64(t_dr["lastUpdateChapterId"].ToString());
                        t_book.SiteId = Convert.ToInt32(t_dr["siteId"].ToString());
                        t_book.SiteName = t_dr["siteName"].ToString();
                        t_book.ChapterCount = t_dr["ChapterCount"] == DBNull.Value ? 0 : Convert.ToInt32(t_dr["ChapterCount"].ToString());
                        t_list.Add(t_book);
                    }
                }
                return t_list;
            }
            catch (Exception ex)
            {
                LogHelper.Error("获取重点更新列表失败" + ex.ToString());
                return null;
            }
        }

        /// <summary>
        /// 获取图书信息
        /// </summary>
        /// <param name="i_book_id"></param>
        /// <returns></returns>
        public BookInfo GetBookInfo(long i_book_id, string i_connect_string)
        {
            return null;
        }

        /// <summary>
        /// 初始化数据库脚本
        /// </summary>
        /// <param name="i_connect_string"></param>
        /// <returns></returns>
        public int InitDBScript(string i_connect_string)
        {
            string t_sql = LoadSqlFromAssembly("DB.txt");
            try
            {
                if (!string.IsNullOrEmpty(t_sql))
                {
                    string[] t_sql_arr = t_sql.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                    if (t_sql_arr != null && t_sql_arr.Length > 0)
                    {
                        foreach (string t_db_sql in t_sql_arr)
                        {
                            DBHelper.ExecuteSql(t_db_sql, i_connect_string);
                        }
                    }

                }
                return 1;
            }
            catch (Exception ex)
            {
                throw new DataException("初始化数据库脚本失败", ex);
            }

        }


        private string LoadSqlFromAssembly(string i_file_name)
        {
            //得到当前程序集对象
            Assembly t_assembly = Assembly.GetExecutingAssembly();
            //创建sql脚本的流对象
            Stream t_strm = t_assembly.GetManifestResourceStream(string.Format("com.crawler.db.SQL2000.{0}", i_file_name));

            //读sql流对象
            StreamReader reader = new StreamReader(t_strm, System.Text.Encoding.Default);
            return reader.ReadToEnd();
        }

        /// <summary>
        /// 获取需要更新的小说队列
        /// </summary>
        /// <param name="i_site_list"></param>
        /// <param name="i_connect_string"></param>
        /// <returns></returns>
        public Queue<SiteUrl> GetUpdateBook(List<BookSiteInfo> i_site_list, int i_page_index, string i_connect_string)
        {
            int t_start_index = (i_page_index - 1) * 10000 + 1;
            int t_end_index = i_page_index * 10000;
            string t_str_sql = string.Format("select a.bookId,a.bookName,b.siteId,a.lastUpdateChapterName, b.chapterListUrl from tbbook a,tbcrawlerbook b where a.bookName=b.bookName and a.bookId>={0} and a.bookId<{1}", t_start_index, t_end_index);

            //存放站点对应的小说集合，这里的50表示有50个站点，这个值可以从数据库获得
            List<SiteUrl>[] t_book_list_arr = new List<SiteUrl>[i_site_list.Count];
            //小说信息
            SiteUrl t_book = null;
            //需要返回的小说队列
            Queue<SiteUrl> t_book_queue = new Queue<SiteUrl>();
            try
            {
                using (SqlConnection t_connection = new SqlConnection(i_connect_string))
                {
                    using (SqlCommand t_cmd = new SqlCommand(t_str_sql, t_connection))
                    {
                        try
                        {
                            t_cmd.CommandTimeout = 600;
                            t_connection.Open();
                            using (SqlDataReader t_reader = t_cmd.ExecuteReader(CommandBehavior.CloseConnection))
                            {
                                //把数据读取到站点对应的小说结合中
                                while (t_reader.Read())
                                {
                                    if (t_reader["lastUpdateChapterName"] != DBNull.Value)
                                    {
                                        if (IsComplateBook(t_reader["lastUpdateChapterName"].ToString()))
                                            continue;
                                    }
                                    if (Convert.ToInt32(t_reader["siteId"].ToString()) == 5)
                                        continue;
                                    t_book = new SiteUrl();
                                    t_book.SiteId = Convert.ToInt32(t_reader["siteId"].ToString());
                                    t_book.BookId = Convert.ToInt64(t_reader["bookId"].ToString());
                                    t_book.Url = t_reader["chapterListUrl"].ToString();
                                    t_book.BookName = t_reader["bookName"].ToString();
                                    t_book.BookType = Consts.BookPageType.ChapterList;
                                    t_book.ChapterOrder = GetChapterOrderType(i_site_list, t_book.SiteId);
                                    //该站点已经读取到小说
                                    if (t_book_list_arr[t_book.SiteId - 1] != null)
                                    {
                                        t_book_list_arr[t_book.SiteId - 1].Add(t_book);
                                    }
                                    else
                                    {
                                        List<SiteUrl> t_book_list = new List<SiteUrl>();
                                        t_book_list.Add(t_book);
                                        t_book_list_arr[t_book.SiteId - 1] = t_book_list;
                                    }
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            LogHelper.Error("获取更新数据失败" + e.ToString());
                        }
                    }
                }


                //那个站点小说最多
                int t_max_book_list_site = 0;

                foreach (List<SiteUrl> t_book_list in t_book_list_arr)
                {
                    if (t_book_list != null && t_book_list.Count > t_max_book_list_site)
                        t_max_book_list_site = t_book_list.Count;
                }

                //一次从一个站点中取一条数据进队列
                for (int index = 0; index < t_max_book_list_site; index++)
                {
                    foreach (List<SiteUrl> t_book_list in t_book_list_arr)
                    {
                        if (t_book_list != null && t_book_list.Count > index)
                        {
                            t_book_queue.Enqueue(t_book_list[index]);
                        }
                    }
                }
                return t_book_queue;

            }
            catch (Exception ex)
            {
                LogHelper.Error("获取更新队列失败" + ex.ToString());
                return null;
            }
        }

        /// <summary>
        /// 是否是已经完本的小说
        /// </summary>
        /// <param name="i_last_update_chatper_name"></param>
        /// <returns></returns>
        private bool IsComplateBook(string i_last_update_chatper_name)
        {

            if (i_last_update_chatper_name.IndexOf("本书完") > -1)
                return true;
            if (i_last_update_chatper_name.IndexOf("新书") > -1)
                return true;

            if (i_last_update_chatper_name.IndexOf("完结") > -1)
                return true;

            if (i_last_update_chatper_name.IndexOf("结局") > -1)
                return true;

            return false;
        }

        /// <summary>
        /// 得到排序方式
        /// </summary>
        /// <param name="i_site_list"></param>
        /// <param name="i_site_id"></param>
        /// <returns></returns>
        private ChapterOrderType GetChapterOrderType(List<BookSiteInfo> i_site_list, int i_site_id)
        {
            ChapterOrderType t_order = ChapterOrderType.ASC;
            foreach (BookSiteInfo t_book_site in i_site_list)
            {
                if (t_book_site.SiteId == i_site_id)
                {
                    t_order = t_book_site.ChapterOrder;
                    break;
                }

            }
            return t_order;
        }

        /// <summary>
        /// 获取小说章节列表
        /// </summary>
        /// <param name="i_book_id"></param>
        /// <param name="i_connect_string"></param>
        /// <returns></returns>
        public List<ChapterInfo> GetChapterByBookId(long i_book_id, string i_connect_string)
        {
            string t_str_sql = string.Format("select bookName,chapterName, chapterId,chapterUrl,isDownLoad from tbchapter where bookId={0}", i_book_id);

            List<ChapterInfo> t_chapter_list = null;

            try
            {
                DataSet t_ds = DBHelper.Query(t_str_sql, i_connect_string);

                if (t_ds != null && t_ds.Tables[0].Rows.Count > 0)
                {
                    t_chapter_list = new List<ChapterInfo>();

                    long t_chapter_id = 0;

                    foreach (DataRow t_row in t_ds.Tables[0].Rows)
                    {
                        if (t_row["isDownLoad"].ToString().Equals("0"))
                        {
                            if (!long.TryParse(t_row["chapterId"].ToString(), out t_chapter_id))
                                t_chapter_id = 0;

                            ChapterInfo t_chapter = new ChapterInfo();
                            t_chapter.BookId = i_book_id;
                            t_chapter.ChapterId = t_chapter_id;
                            t_chapter.ChapterUrl = t_row["chapterUrl"].ToString();
                            t_chapter.BookName = t_row["bookName"].ToString();
                            t_chapter.ChapterName = t_row["chapterName"].ToString();
                            t_chapter.IsDownLoad = t_row["isDownLoad"] == DBNull.Value ? 0 : Convert.ToInt32(t_row["isDownLoad"].ToString());
                            t_chapter_list.Add(t_chapter);
                        }
                    }
                }

                return t_chapter_list;
            }
            catch (Exception ex)
            {
                LogHelper.Error("获取小说章节列表失败" + ex.ToString());
                return null;
            }
        }

        /// <summary>
        /// 添加热点排行榜小说
        /// </summary>
        /// <param name="i_book_name"></param>
        /// <param name="i_book_source"></param>
        /// <param name="i_connect_string"></param>
        /// <returns></returns>
        public long AddTopBook(string i_book_name, Consts.BookSource i_book_source, string i_connect_string)
        {
            string t_str_sql = string.Format("select count(*) totalcount from tbtopbook where bookName='{0}'", i_book_name);

            try
            {
                DataSet t_ds = DBHelper.Query(t_str_sql, i_connect_string);
                int t_count = 0;
                if (t_ds != null && t_ds.Tables[0].Rows.Count > 0)
                {
                    if (!int.TryParse(t_ds.Tables[0].Rows[0]["totalcount"].ToString(), out t_count))
                        t_count = 0;

                }

                if (t_count == 0)
                {
                    t_str_sql = string.Format("insert into tbtopbook(bookName,bookType,createTime)values('{0}',{1},'{2}')", i_book_name, (int)i_book_source, DateTime.Now);
                    DBHelper.ExecuteSql(t_str_sql, i_connect_string);
                }

                t_str_sql = string.Format("select bookid from tbbook where bookName='{0}'", i_book_name);
                t_count = 0;
                t_ds = DBHelper.Query(t_str_sql, i_connect_string);
                if (t_ds != null && t_ds.Tables[0].Rows.Count > 0)
                {
                    if (!int.TryParse(t_ds.Tables[0].Rows[0]["bookid"].ToString(), out t_count))
                        t_count = 0;
                }

                if (t_count > 0)
                {
                    AddBookClick(t_count, i_connect_string);
                }

                return t_count;
            }
            catch (Exception ex)
            {
                LogHelper.Error("添加热点排行榜小说失败" + ex.ToString());
                return -1;
            }
        }

        /// <summary>
        /// 添加图书点击
        /// </summary>
        /// <param name="i_book_id"></param>
        /// <param name="i_connect_string"></param>
        public void AddBookClick(long i_book_id, string i_connect_string)
        {
            
            string t_str_sql = string.Format("select count(*) totalcount from tbbookclick where bookId={0}", i_book_id);

            try
            {
                DataSet t_ds = DBHelper.Query(t_str_sql, i_connect_string);
                int t_count = 0;
                if (t_ds != null && t_ds.Tables[0].Rows.Count > 0)
                {
                    if (!int.TryParse(t_ds.Tables[0].Rows[0]["totalcount"].ToString(), out t_count))
                        t_count = 0;
                }
                if (t_count > 0)
                    t_str_sql = string.Format("update tbbookclick set clickcount=clickcount+10 where bookId={0}", i_book_id);
                else
                    t_str_sql = string.Format("insert tbbookclick(bookId,clickcount,existicon)values({0},10,1)", i_book_id);

                DBHelper.ExecuteSql(t_str_sql, i_connect_string);
            }
            catch (Exception ex)
            {
                LogHelper.Error("添加热点图书点击失败" + ex.ToString());

            }
        }

        /// <summary>
        /// 获取小说的章节地址列表
        /// </summary>
        /// <param name="i_book_id"></param>
        /// <param name="i_connect_string"></param>
        /// <returns></returns>
        public List<BookUrlInfo> GetBookUrlByBookId(long i_book_id, string i_connect_string)
        {
            string t_str_sql = string.Format("select chapterListUrl,host,bits,startIndex,startSign,endSign from tbbookUrl where bookId={0}", i_book_id);

            List<BookUrlInfo> t_list = new List<BookUrlInfo>();

            BookUrlInfo t_book_url = null;

            try
            {
                using (SqlConnection t_connection = new SqlConnection(i_connect_string))
                {
                    using (SqlCommand t_cmd = new SqlCommand(t_str_sql, t_connection))
                    {

                        t_cmd.CommandTimeout = 600;
                        t_connection.Open();
                        using (SqlDataReader t_reader = t_cmd.ExecuteReader(CommandBehavior.CloseConnection))
                        {

                            while (t_reader.Read())
                            {

                                t_book_url = new BookUrlInfo();
                                t_book_url.BookId = i_book_id;
                                t_book_url.ChapterListUrl = t_reader["chapterListUrl"].ToString();
                                t_book_url.Host = t_reader["host"].ToString();
                                t_book_url.Bits = int.Parse(t_reader["bits"].ToString());
                                t_book_url.SartIndex = t_reader["startIndex"] == DBNull.Value ? 0 : Convert.ToInt32(t_reader["startIndex"].ToString());
                                t_book_url.StartSign = t_reader["startSign"] == DBNull.Value ? "" : t_reader["startSign"].ToString();
                                t_book_url.EndSign = t_reader["endSign"] == DBNull.Value ? "" : t_reader["endSign"].ToString();
                                t_list.Add(t_book_url);
                            }
                        }

                    }
                }
            }
            catch (Exception e)
            {
                LogHelper.Error("获取小说章节地址" + e.ToString());
            }

            return t_list;
        }

        /// <summary>
        /// 添加小说URL
        /// </summary>
        /// <param name="i_book_url"></param>
        /// <returns></returns>
        public int AddBookUrl(BookUrlInfo i_book_url, string i_connect_string)
        {
            string t_str_sql = string.Format("select count(*) totalcount from tbbookUrl where bookId={0} and host='{1}'", i_book_url.BookId, i_book_url.Host);

            try
            {
                DataSet t_ds = DBHelper.Query(t_str_sql, i_connect_string);
                int t_count = 0;
                if (t_ds != null && t_ds.Tables[0].Rows.Count > 0)
                {
                    if (!int.TryParse(t_ds.Tables[0].Rows[0]["totalcount"].ToString(), out t_count))
                        t_count = 0;
                }

                i_book_url.ChapterListUrl = i_book_url.ChapterListUrl.Replace("'", "''");
                i_book_url.StartSign = i_book_url.StartSign.Replace("'", "''");
                i_book_url.EndSign = i_book_url.EndSign.Replace("'", "''");

                if (t_count > 0)
                {
                    t_str_sql = string.Format("update tbbookUrl set bits={0},startIndex={1},startSign='{2}',endSign='{3}' where bookId={4} and host='{5}'", i_book_url.Bits, i_book_url.SartIndex, i_book_url.StartSign, i_book_url.EndSign, i_book_url.BookId, i_book_url.Host);
                }
                else
                {

                    t_str_sql = string.Format("insert tbbookUrl(bookId,host,bits,chapterlisturl,startIndex,startSign,endSign)values({0},'{1}',{2},'{3}',{4},'{5}','{6}')",
                        i_book_url.BookId, i_book_url.Host, i_book_url.Bits, i_book_url.ChapterListUrl, i_book_url.SartIndex, i_book_url.StartSign, i_book_url.EndSign);
                }

                return DBHelper.ExecuteSql(t_str_sql, i_connect_string);
            }
            catch (Exception ex)
            {
                LogHelper.Error("添加小说URL" + ex.ToString());
                return -1;
            }
        }

        public List<BookUrlInfo> GetICONBookList(string i_connect_string)
        {
            string t_str_sql = "select bookId,chapterListUrl,isdownload, siteId from tbbook where siteId in(21,22) and status=2";

            List<BookUrlInfo> t_list = new List<BookUrlInfo>();

            BookUrlInfo t_book_url = null;

            try
            {
                using (SqlConnection t_connection = new SqlConnection(i_connect_string))
                {
                    using (SqlCommand t_cmd = new SqlCommand(t_str_sql, t_connection))
                    {

                        t_cmd.CommandTimeout = 600;
                        t_connection.Open();
                        using (SqlDataReader t_reader = t_cmd.ExecuteReader(CommandBehavior.CloseConnection))
                        {

                            while (t_reader.Read())
                            {

                                t_book_url = new BookUrlInfo();
                                t_book_url.BookId = Convert.ToInt64(t_reader["bookId"].ToString());
                                if (t_reader["siteId"].ToString().Equals("21"))
                                {
                                    t_book_url.ChapterListUrl = t_reader["chapterListUrl"].ToString().ToLower().Replace("bookreader", "book");
                                }
                                else
                                {
                                    t_book_url.ChapterListUrl = t_reader["chapterListUrl"].ToString().ToLower().Replace("bookreader", "mmweb");
                                }
                                if (t_reader["isdownload"] != DBNull.Value)
                                {
                                    t_book_url.SartIndex = int.Parse(t_reader["isdownload"].ToString());
                                }
                               

                                t_list.Add(t_book_url);
                            }
                        }

                    }
                }
            }
            catch (Exception e)
            {
                LogHelper.Error("获取小说章节地址" + e.ToString());
            }

            return t_list;
        }

        public int UpdateBookUrl(long i_book_id,string i_icon_url, string i_connect_string)
        {
            string t_str_sql = string.Empty;

            if (string.IsNullOrEmpty(i_icon_url))
            {
                t_str_sql = string.Format("update tbbook set isDownload=-1 where bookId={0}", i_book_id);
                DBHelper.ExecuteSql(t_str_sql, i_connect_string);
                return 0;
            }
            t_str_sql = string.Format("update tbbook set ICONURL='{0}' where bookId={1}", i_icon_url, i_book_id);

            try
            {
                return DBHelper.ExecuteSql(t_str_sql, i_connect_string);
            }
            catch (Exception ex)
            {
                LogHelper.Error("更新小说封面地址失败" + ex.ToString());
                return -1;
            }
        }


    }
}
